#!/usr/bin/env python3
"""
远程服务器验证脚本
用法: python verify_remote_setup.py
"""

import os
import sys
import subprocess
import json
from pathlib import Path
from datetime import datetime

# 颜色定义
class Colors:
    HEADER = '\033[95m'
    BLUE = '\033[94m'
    CYAN = '\033[96m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    RED = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

def print_header(text):
    """打印标题"""
    print(f"\n{Colors.BLUE}{'='*60}{Colors.ENDC}")
    print(f"{Colors.BLUE}{text}{Colors.ENDC}")
    print(f"{Colors.BLUE}{'='*60}{Colors.ENDC}\n")

def print_success(text):
    """打印成功信息"""
    print(f"{Colors.GREEN}✅ {text}{Colors.ENDC}")

def print_error(text):
    """打印错误信息"""
    print(f"{Colors.RED}❌ {text}{Colors.ENDC}")

def print_warning(text):
    """打印警告信息"""
    print(f"{Colors.YELLOW}⚠️  {text}{Colors.ENDC}")

def print_info(text):
    """打印信息"""
    print(f"{Colors.CYAN}ℹ️  {text}{Colors.ENDC}")

def check_file_exists(filepath, description):
    """检查文件是否存在"""
    if os.path.exists(filepath):
        print_success(f"{description} 存在")
        return True
    else:
        print_error(f"{description} 不存在")
        return False

def check_file_contains(filepath, pattern, description):
    """检查文件是否包含特定内容"""
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            content = f.read()
            if pattern in content:
                print_success(f"{description} 已找到")
                return True
            else:
                print_error(f"{description} 未找到")
                return False
    except Exception as e:
        print_error(f"读取文件失败: {e}")
        return False

def check_python_syntax(filepath):
    """检查 Python 文件语法"""
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            compile(f.read(), filepath, 'exec')
        print_success(f"{filepath} 语法正确")
        return True
    except SyntaxError as e:
        print_error(f"{filepath} 语法错误: {e}")
        return False

def check_module_import(module_name):
    """检查模块是否可导入"""
    try:
        __import__(module_name)
        print_success(f"模块 {module_name} 已安装")
        return True
    except ImportError:
        print_warning(f"模块 {module_name} 未安装")
        return False

def get_git_log(num_commits=5):
    """获取 Git 提交历史"""
    try:
        result = subprocess.run(
            ['git', 'log', '--oneline', f'-{num_commits}'],
            capture_output=True,
            text=True,
            check=True
        )
        return result.stdout.strip().split('\n')
    except Exception as e:
        print_error(f"获取 Git 日志失败: {e}")
        return []

def verify_code():
    """验证代码"""
    print_header("1️⃣  代码验证")
    
    results = []
    
    # 检查接口
    result = check_file_contains(
        'main.py',
        'process-video-text-only',
        '/process-video-text-only 接口'
    )
    results.append(result)
    
    # 检查方法
    result = check_file_contains(
        'video_processor.py',
        'process_video_text_only',
        'process_video_text_only() 方法'
    )
    results.append(result)
    
    # 检查 sanitize_for_json 函数
    result = check_file_contains(
        'main.py',
        'sanitize_for_json',
        'sanitize_for_json() 函数'
    )
    results.append(result)
    
    return all(results)

def verify_documentation():
    """验证文档"""
    print_header("2️⃣  文档验证")
    
    docs = [
        ('TEXT_ONLY_API.md', 'API 文档'),
        ('TEXT_ONLY_QUICK_START.md', '快速开始指南'),
        ('TEXT_ONLY_FEATURE_SUMMARY.md', '功能总结'),
        ('NEW_FEATURE_IMPLEMENTATION.md', '实现总结'),
        ('REMOTE_VERIFICATION.md', '远程验证指南'),
    ]
    
    results = []
    for filepath, description in docs:
        result = check_file_exists(filepath, description)
        results.append(result)
    
    print_info(f"文档文件总数: {sum(results)}/{len(docs)}")
    return all(results)

def verify_git():
    """验证 Git 提交"""
    print_header("3️⃣  Git 提交验证")
    
    commits = get_git_log(5)
    
    if commits:
        print_info("最新 5 个提交:")
        for commit in commits:
            print(f"  {commit}")
        
        # 检查是否有新功能提交
        has_feature_commit = any('process-video-text-only' in commit or '文本识别' in commit for commit in commits)
        
        if has_feature_commit:
            print_success("新功能提交已找到")
            return True
        else:
            print_warning("未找到新功能提交，但代码已更新")
            return True
    else:
        print_error("无法获取 Git 提交历史")
        return False

def verify_syntax():
    """验证 Python 语法"""
    print_header("4️⃣  Python 语法验证")
    
    files = [
        'main.py',
        'video_processor.py',
    ]
    
    results = []
    for filepath in files:
        if os.path.exists(filepath):
            result = check_python_syntax(filepath)
            results.append(result)
        else:
            print_error(f"文件 {filepath} 不存在")
            results.append(False)
    
    return all(results)

def verify_dependencies():
    """验证依赖"""
    print_header("5️⃣  依赖验证")
    
    packages = [
        'fastapi',
        'starlette',
        'cv2',
        'numpy',
        'paddle',
    ]
    
    results = []
    for package in packages:
        result = check_module_import(package)
        results.append(result)
    
    return all(results)

def verify_api_endpoints():
    """验证 API 端点"""
    print_header("6️⃣  API 端点验证")
    
    # 检查所有端点是否都存在
    endpoints = [
        ('/health', 'GET /health'),
        ('/process-video', 'POST /process-video'),
        ('/process-video-with-output', 'POST /process-video-with-output'),
        ('/process-video-text-only', 'POST /process-video-text-only'),
    ]
    
    results = []
    for endpoint, description in endpoints:
        result = check_file_contains('main.py', endpoint, description)
        results.append(result)
    
    return all(results)

def generate_report(results):
    """生成验证报告"""
    print_header("📊 验证报告")
    
    total = len(results)
    passed = sum(results)
    failed = total - passed
    
    print(f"总验证项: {total}")
    print(f"{Colors.GREEN}通过: {passed}{Colors.ENDC}")
    print(f"{Colors.RED}失败: {failed}{Colors.ENDC}")
    
    if failed == 0:
        print(f"\n{Colors.GREEN}{Colors.BOLD}✅ 所有验证项目已通过！{Colors.ENDC}")
        return True
    else:
        print(f"\n{Colors.RED}{Colors.BOLD}❌ 有 {failed} 个验证项目失败{Colors.ENDC}")
        return False

def main():
    """主函数"""
    print(f"\n{Colors.BOLD}{Colors.BLUE}╔════════════════════════════════════════════════════════════╗{Colors.ENDC}")
    print(f"{Colors.BOLD}{Colors.BLUE}║{Colors.ENDC}  远程服务器验证脚本")
    print(f"{Colors.BOLD}{Colors.BLUE}║{Colors.ENDC}  验证时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"{Colors.BOLD}{Colors.BLUE}╚════════════════════════════════════════════════════════════╝{Colors.ENDC}")
    
    # 检查是否在项目目录中
    if not os.path.exists('main.py'):
        print_error("未找到 main.py，请在项目根目录中运行此脚本")
        sys.exit(1)
    
    print_info(f"项目路径: {os.getcwd()}")
    
    # 执行验证
    results = []
    
    try:
        results.append(verify_code())
        results.append(verify_documentation())
        results.append(verify_git())
        results.append(verify_syntax())
        results.append(verify_dependencies())
        results.append(verify_api_endpoints())
    except Exception as e:
        print_error(f"验证过程中出错: {e}")
        sys.exit(1)
    
    # 生成报告
    success = generate_report(results)
    
    # 打印下一步
    print_header("📞 下一步")
    print("1. 启动服务:")
    print("   python main.py")
    print("")
    print("2. 测试接口:")
    print("   curl -X POST http://localhost:8000/process-video-text-only -F 'file=@test.mp4'")
    print("")
    print("3. 查看文档:")
    print("   cat TEXT_ONLY_QUICK_START.md")
    print("")
    
    sys.exit(0 if success else 1)

if __name__ == '__main__':
    main()

